package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(urlPatterns = {"/admin/*"})
public class AdminLoginCheckedFilter implements Filter {
    private boolean isLoggedIn(HttpServletRequest httpServletRequest){
        boolean sessionLog =
                httpServletRequest.getSession().getAttribute("admin") != null;
        boolean cookiesLog =false;
        for(Cookie cookie : httpServletRequest.getCookies()){
            if(cookie.getName().equals("AdminIsLogin")){
                cookiesLog = true;
            }
        }
        return sessionLog || cookiesLog;
    }
    @Override
    public void init(FilterConfig filterConfig) {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        // 检查是否已经登录
        if (isLoggedIn(httpServletRequest)||requestURI.startsWith("/admin/login"))
        {
            // 已登录，继续处理请求
            // 或者去访问登录页
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else{
            // 未登录，重定向到登录页面或返回错误响应
            System.out.println("filter");
            String loginPath = "/admin/login"; // 登录页面的路径
            httpServletResponse.sendRedirect(loginPath); // 重定向到登录页面  
        }
    }
    @Override
    public void destroy() {
    }
}